package com.sfac.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author:唐琳的爹
 * @BelongsProject:hqyj_springboot
 * @BelongsPackage:com.sfac.aop
 * @CreateTime:2022/8/22 14:39:54
 */
@Aspect
@Slf4j
@Component
public class MyAop {

    // 制定切点,切入在自己自定的注解的方法处
    @Pointcut("@annotation(com.sfac.aop.MyAnnotation)")
    @Order(1)
    public void point(){};


    // 使用自定的切入点注解
    @Around("point()")
    public Object aroundAnnotationAop(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long beginTime = System.currentTimeMillis();
        Object o = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
        long endTime = System.currentTimeMillis();
        log.info("使用的时间为{}",(endTime-beginTime));
        return o;
    }



    // ===================================================
    // 制定切点(Controller层下的所有方法)
    @Pointcut("execution(public * com.sfac.modules.*.controller.*.*(..))")
    // 设置优先级(越小越先)
    @Order(1)
    public void pt(){}

    @Before("pt()")
    public void beforeControllerAop(JoinPoint joinPoint){
        log.info("before controller");
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attr.getRequest();
        log.info(request.getContextPath());
        log.info(request.getServletPath());
        log.info(request.getMethod());
    }

    @Around("pt()")
    public Object aroundControllerAop(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        log.info("around controller");
        return proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
    }


    @After("pt()")
    public void afterControllerAop(JoinPoint joinPoint){
        log.info("after controller");
    }

}
